package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.DataException;
import com.sky.mapper.common.MerchantMapper;
import com.sky.mapper.common.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {

    private final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 小程序的用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Result<UserLoginVO> login(UserLoginDTO userLoginDTO) {
        //1. 校验参数是否合法
        if(null == userLoginDTO || null == userLoginDTO.getCode()){
            throw new DataException(MessageConstant.DATA_ERROR);
        }

        //2. 通过参数请求微信的api 获取openID
        String openId = getOpenId(userLoginDTO);

        //3. 通过openID查询用户表 判断当前用户是否已经注册过 如果没有则注册
        User user = userMapper.selectByOpenId(openId);
        if(null == user){
            //用户是一个新的用户 我们需要先注册 然后在返回
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());

            userMapper.insert(user); //这个新增需要返回新增数据的id
        }

        //4. 通过jwt的工具类生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        //4.1 查询店铺的信息
        Merchant merchant = merchantMapper.selectById(1L);

        //4.3 计算商家到用户的配送费用
            //4.3.1 通过商家的地址 调用高德地图获取到坐标
        String location = MapUtils.addressToLnglat(merchant.getShopAddress());
        //4.3.2 通过商家的坐标和用户的坐标计算距离 然后通过距离计算费用
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(location, userLoginDTO.getLocation());

        //5. 构建返回值并返回
        UserLoginVO vo = UserLoginVO.builder()
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(merchant.getId())
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(delivoryCost)
                .build();
        return Result.success(vo);
    }

    /**
     * 调用微信的api完成openid的获取
     * @param userLoginDTO
     * @return
     */
    private String getOpenId(UserLoginDTO userLoginDTO) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        Map map = JSON.parseObject(json, Map.class);
        return map.get("openid").toString();
    }
}
